package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口，获取openid
        //选择HashMap是因为微信接口要求参数以键值对（key-value） 形式传递，而HashMap是最适合存储键值对的集合，且支持动态添加参数。
      Map<String, String> map = new HashMap<>();//封装参数
      map.put("appid", weChatProperties.getAppid());//微信公众号的appid
      map.put("secret", weChatProperties.getSecret());//微信公众号的密钥
      map.put("js_code", userLoginDTO.getCode());//微信返回的临时登录凭证code
      map.put("grant_type", "authorization_code");//授权类型,固定值
        //调用微信接口，获取openid
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, map);
        //解析结果
        JSONObject jsonObject = JSON.parseObject(json);
        //获取openid
        String openid = jsonObject.getString("openid");
        //判断openid是否为空，为空则登录失败，抛出登录失败异常
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断是否已存在该用户，不存在则自动完成注册
         User user = userMapper.getByOpenid(openid);
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            //保存用户数据
             userMapper.insert(user);
        }

        return user;
    }
}
